//
//  YXYSearchsViewController.m
//  Topit
//
//  Created by dllo on 15/12/12.
//  Copyright © 2015年 YXY. All rights reserved.
//

#import "YXYSearchsViewController.h"
#import "YXYGroupSearchDataModel.h"
#import "YXYSearchShowViewController.h"
@interface YXYSearchsViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) NSMutableArray *tags;
@property (nonatomic, retain) NSMutableArray *searchData;
@property (nonatomic, retain) NSMutableArray *searchHot;


@end

@implementation YXYSearchsViewController

- (void)dealloc {
    [_searchBar release];
    [_tableView release];
    [_tags release];
    [_searchData release];
    [_searchHot release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.searchData = [NSMutableArray arrayWithCapacity:0];
    self.searchHot = [NSMutableArray arrayWithCapacity:0];

    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, self.view.width, 44)];
    self.searchBar.delegate = self;
    self.searchBar.barStyle = UIBarStyleDefault;
    self.searchBar.placeholder = @"搜索";
    self.searchBar.keyboardType = UIKeyboardTypeNamePhonePad;
    [self.view addSubview:_searchBar];
    [_searchBar release];
    
    [self getDate];
    [self setUpTableView];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated {
    [_searchBar becomeFirstResponder];
}
#pragma mark - 网络请求
- (void)getDate {
    self.tags = [NSMutableArray arrayWithCapacity:0];
    [YXYNetWorkTool getWithUrl:KsearchURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        for (NSDictionary *dic in result[@"item"]) {
            YXYGroupSearchModel *groupSearchModel = [[YXYGroupSearchModel alloc] initWithDictionary:dic];
            [_tags addObject:groupSearchModel];
            [groupSearchModel release];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
    } fail:^(NSError *error) {
        
    }];
}
#pragma mark - tableView
- (void)setUpTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 65, self.view.width, self.view.height) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    [self.view addSubview:self.tableView];
    [_tableView release];
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchHot.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    YXYSelectionModel *selectionHot = self.searchHot[indexPath.row];
   
    NSRange range = [selectionHot.name rangeOfString:_searchBar.text];
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:selectionHot.name];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range.location, range.length)];
//    cell.textLabel.text = selectionHot.name;
    cell.textLabel.attributedText = string;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YXYSelectionModel *selectionHot = self.searchHot[indexPath.row];
    NSString *searchtext = [kSearchportURL stringByAppendingString:[selectionHot.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    YXYSearchShowViewController *searchShowVC = [[YXYSearchShowViewController alloc] initWithURL:searchtext WithName:selectionHot.name];
    [self presentViewController:searchShowVC animated:YES completion:^{
        
    }];
    [searchShowVC release];

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

#pragma mark - 尾视图
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 160;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:self.view.bounds];
    for (int i = 0; i < self.tags.count; i++) {
        YXYSelectionModel *selectionModel = self.tags[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.tag = 1000 + i;
        button.frame = CGRectMake(i % 6 * view.width / 6, i / 6 * 30, view.width / 6, 20);
        [button setTitle:selectionModel.name forState:UIControlStateNormal];
        [button addTarget:self action:@selector(shortcutDidPress:) forControlEvents:UIControlEventTouchUpInside];
        [view addSubview:button];

    }
    return view;
}

- (void)shortcutDidPress:(UIButton *)sender {
    YXYSelectionModel *selectionModel = self.tags[sender.tag - 1000];
    NSString *searchtext = [kSearchportURL stringByAppendingString:[selectionModel.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    YXYSearchShowViewController *searchShowVC = [[YXYSearchShowViewController alloc] initWithURL:searchtext WithName:selectionModel.name];
    [self presentViewController:searchShowVC animated:YES completion:^{
        
    }];
    [searchShowVC release];

}
#pragma mark - searchBar
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    [self.searchHot removeAllObjects];
    NSString *searchURL = [kSearchRelatedURL stringByAppendingString:[searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    self.tags = [NSMutableArray arrayWithCapacity:0];
    [YXYNetWorkTool getWithUrl:searchURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        for (NSDictionary *dic in result[@"item"]) {
            YXYGroupSearchModel *groupSearchModel = [[YXYGroupSearchModel alloc] initWithDictionary:dic];
            [self.searchHot addObject:groupSearchModel];
            [groupSearchModel release];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_tableView reloadData];
        });
    } fail:^(NSError *error) {
        
    }];
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *searchtext = [kSearchportURL stringByAppendingString:[searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    YXYSearchShowViewController *searchShowVC = [[YXYSearchShowViewController alloc] initWithURL:searchtext WithName:searchBar.text];
    [self presentViewController:searchShowVC animated:YES completion:^{
        
    }];
    [searchShowVC release];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    searchBar.showsCancelButton = YES;
    for(id cc in [searchBar subviews])
    {
        if([cc isKindOfClass:[UIButton class]])
        {
            UIButton *btn = (UIButton *)cc;
            [btn setTitle:@"取消"  forState:UIControlStateNormal];
        }
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
